package jf.myfristservice;

import java.util.Date;

import jf.myfristservice.MyService.LocalBinder;
import jf.myfristservice.Rundgangsview;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import jf.myfristservice.R;

public class MainActivity extends Activity {

	private static  boolean activityVisible;
	private Intent svc;
	private long maximumlaunchdelaySeconds = 120;		// Maximum wait time before song begins to play
	private long musicplayTime = 120;					//Time music playing
	private MusicTimer oMusicTimer;
	private long reativeDelay	=	-1;
	
	//UI
	private TextView oTextview;
	private ProgressBar	oProgressBar;
	
	//Service binding variales
	private MyService mService;
    boolean mBound = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		/*
		 *  Bind service to Activity
		 */
		svc	= new Intent(getBaseContext(),MyService.class);
		startService(svc);
		bindService(svc, mConnection, Context.BIND_AUTO_CREATE);
		//---------------------------------------------------
		
		/*
		 * Button for Ends App just for Testing
		 * */
		Button button1 = (Button) findViewById(R.id.button1);
		button1.setOnClickListener(myhandler1);
		//---------------------------------------------------

		/*
		 * Textview for Progress Description
		 * */		
		oTextview	= (TextView) findViewById(R.id.timer);
		//---------------------------------------------------

		/*
		 * ProgressBar
		 * */		
		oProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
		//---------------------------------------------------

		
		/*
		 * Setup and start Timer
		 * */		
		if(reativeDelay< 0){
			
			this.reativeDelay	= this.getDelay();
		}
		
		Timer oTimer	= new Timer(this.getDelay(), 1000,this);
		oTimer.start();
		//---------------------------------------------------


		/*
		 * Setup and start Timer
		 * */		
		oMusicTimer	= new MusicTimer(this.getPlaytime(), 1000,this);

		//---------------------------------------------------
		
		
		/*Rundgangsview black_hole = (Rundgangsview)findViewById(R.id.black_hole);
		black_hole.disable_touch(true);*/		
	}
	
	public void setTimerTextView(long millisUntilFinished){
		
		long remainingSeconds	= 	millisUntilFinished / 1000;
		
		//Using get delay() to divide the remaining time
		double progressStatus	=	((double)(this.getDelay()) /  (double)this.reativeDelay);
		int	progressBarVal		=	oProgressBar.getMax() - (int)(progressStatus*100);
		
		if( 0.80 < progressStatus){
			oTextview.setText("Loading");
			Log.w("Loading", "Loading:"+ progressStatus );
		}
		
		if( 0.60 < progressStatus){
			oTextview.setText("Initialisieren");
			Log.w("Initialisieren", "Initialisieren:" + remainingSeconds);
		}
		
		if( 0.30 < progressStatus){
			oTextview.setText("Starting");		
			Log.w("Starting", "Starting:" + remainingSeconds);
		}
		
		if( 0.30 > progressStatus){
			oTextview.setText("Waiting");		
			Log.w("Starting", "Starting:" + remainingSeconds);
		}
		
		
		
		Log.w("progressBarVal","progressBarVal:"+progressBarVal);
		oProgressBar.setProgress(progressBarVal);
	}

	public void setTimerTextViewCountdown(long millisUntilFinished){
		
		long remainingSeconds	= 	millisUntilFinished / 1000;
		int	progressBarVal		=	oProgressBar.getMax() - (((int)(remainingSeconds)/oProgressBar.getMax())*100);
		
		oTextview.setText("" + remainingSeconds);		

		Log.w("progressBarVal","progressBarVal:"+progressBarVal);
		oProgressBar.setProgress(progressBarVal);
	}
		
	/*
	 * Tell the Service that the Timer have been finished
	 */
	public void TimerEnd(){
		
		Log.w("TT","mBound if");
		oTextview.setText("Started");
		
		if(mBound){
			Log.w("TT","mBound true");
			this.oMusicTimer.start();
			this.mService.setTimerFinished(true);
		}
	}
	//---------------------------------------------------
	
    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
        	
        	Log.w("SVC", "SVC Connected");
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            Log.w("SVC", "mBound ? true");
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
    /** ---------------------------------------------------*/
    
    
	/*
	 *  Implements Testbutton
	 */    
	View.OnClickListener myhandler1 = new View.OnClickListener() {
		  public void onClick(View v) {
		    	stopService(svc); 
		    	 System.exit(0);
		  }
	 };
	//---------------------------------------------------
	 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		
		return true;
	}
	
	
	/*	#############################################################################################
	 * 	Functions stores and update information
	 *	if APP is in back or foreground
	 * ##############################################################################################
	 */
	public static boolean isActivityVisible() {
	  Log.w("myApp", "isActivityVisible");
	    return activityVisible;
	}  

	public static  void activityResumed() {
		activityVisible = true;
	}

	public static  void activityPaused() {
		Log.w("myApp", "activityPaused");
		activityVisible = false;
	}	
	
	@Override
	protected void onResume() {
		super.onResume();
		MainActivity.activityResumed();
	}

	@Override
	protected void onPause() {
		Log.w("myApp", "OnPause");
		MainActivity.activityPaused();
		super.onPause();
	}	
	//-----------------------------------------------------------------------------------------------
	
	/*
	 * 	Disable userinteractions
	 */
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

		return false;
    }

	
	/*	#############################################################################################
	 * 	Functions calculates delay of starting the
	 *  music
	 * ##############################################################################################
	 */	
	private long getDelay(){
		
		Date date=new Date() ;  
		Log.w("Zeit","Zeit:"+  date.getTime() % (maximumlaunchdelaySeconds*1000));
		return maximumlaunchdelaySeconds*1000 - (date.getTime() % (maximumlaunchdelaySeconds*1000)); 	//Timer time is set to time of the next passed 10 minutes
																										// Program start is set to every 600 seconds
	}
	
	private long getPlaytime(){

		return this.musicplayTime * 1000;
	}
	
	
	//-----------------------------------------------------------------------------------------------
	
    @Override
    protected void onStop() {
        super.onStop();
        Log.e("onstop","onstop");
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }        
    }
    
    public void endAPP(){
    	this.onStop();
    	stopService(svc);
    	System.exit(0);
    }
}
